package com.muyu.danmo.controller;


import com.muyu.common.core.domain.Result;
import com.muyu.common.core.utils.DateUtils;
import com.muyu.common.core.utils.poi.ExcelUtil;
import com.muyu.common.core.web.controller.BaseController;
import com.muyu.common.log.annotation.Log;
import com.muyu.common.log.enums.BusinessType;
import com.muyu.common.security.utils.DescribeFaceVerify;
import com.muyu.common.security.utils.InitFaceVerify;
import com.muyu.common.security.utils.SecurityUtils;
import com.muyu.common.system.domain.LoginUser;
import com.muyu.danmo.domain.DanmoInformationCopy1;
import com.muyu.danmo.domain.mapstruct.PersonMapper;
import com.muyu.danmo.domain.vo.PersonBaseInfoVO;
import com.muyu.danmo.domain.vo.PersonNameVO;
import com.muyu.danmo.req.DanmoProvincesCities;
import com.muyu.danmo.service.IDanmoInformationCopy1Service;
import com.muyu.danmo.service.impl.AggregationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 个人信息新Controller
 * 
 * @author yangle
 * @date 2024-12-10
 */
@RestController
@RequestMapping("/danmoInformationCopy1")
public class DanmoInformationCopy1Controller extends BaseController
{
    @Autowired
    private IDanmoInformationCopy1Service danmoInformationCopy1Service;

    @Autowired
    private AggregationService aggregationService;

    @Autowired
    private PersonMapper personMapper;


    /**
     * 查询个人信息新列表
     */
//    @RequiresPermissions("system:danmoInformationCopy1:list")
    @PostMapping("/list")
    public Result<List<PersonNameVO>> list(@RequestBody DanmoInformationCopy1 danmoInformationCopy1)
    {
        if (danmoInformationCopy1.getName()==null || danmoInformationCopy1.getName().equals("")){
            return Result.error("查询名字不能为空");
        }
        List<PersonNameVO> personName = danmoInformationCopy1Service.getPersonName(danmoInformationCopy1);
//        List<DanmoInformationCopy1> list = danmoInformationCopy1Service.selectDanmoInformationCopy1List(danmoInformationCopy1);
        return Result.success(personName);
    }

    /**
     * 导出个人信息新列表
     */
//    @RequiresPermissions("system:danmoInformationCopy1:export")
    @Log(title = "个人信息新", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DanmoInformationCopy1 danmoInformationCopy1)
    {
        List<DanmoInformationCopy1> list = danmoInformationCopy1Service.selectDanmoInformationCopy1List(danmoInformationCopy1);
        ExcelUtil<DanmoInformationCopy1> util = new ExcelUtil<DanmoInformationCopy1>(DanmoInformationCopy1.class);
        util.exportExcel(response, list, "个人信息新数据");
    }

    /**
     * 获取个人信息新详细信息
     */
//    @RequiresPermissions("system:danmoInformationCopy1:query")
    @PostMapping("/viewDetails")
    public Result getInfo(@RequestBody DanmoInformationCopy1 danmoInformationCopy1)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser==null){
            return Result.notLoggedIn("请登录");
        }
        return success(danmoInformationCopy1Service.selectDanmoInformationCopy1ById(danmoInformationCopy1));
    }

    /**
     * 新增个人信息新
     */
//    @RequiresPermissions("system:danmoInformationCopy1:add")
    @Log(title = "个人信息新", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public Result add(@RequestBody DanmoInformationCopy1 danmoInformationCopy1) throws UnsupportedEncodingException {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser==null){
            return Result.notLoggedIn("请登录");
        }
        danmoInformationCopy1.setUserId(loginUser.getUserid());
        return danmoInformationCopy1Service.insertDanmoInformationCopy1(danmoInformationCopy1);
    }

    /**
     * 新增个人信息
     */
    @Log(title = "个人信息", businessType = BusinessType.INSERT)
    @PostMapping("/addDanmoInformation")
    public Result addDanmoInformation(@RequestBody DanmoInformationCopy1 danmoInformationCopy1)  {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser==null){
            return Result.notLoggedIn("请登录");
        }
        danmoInformationCopy1.setUserId(loginUser.getUserid());
        return danmoInformationCopy1Service.addDanmoInformation(danmoInformationCopy1);
    }

    /**
     * 修改个人信息新
     */
//    @RequiresPermissions("system:danmoInformationCopy1:edit")
    @Log(title = "个人信息新", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public Result edit(@RequestBody DanmoInformationCopy1 danmoInformationCopy1) throws UnsupportedEncodingException {
        return danmoInformationCopy1Service.updateDanmoInformationCopy1(danmoInformationCopy1);
    }

    /**
     * 删除个人信息新
     */
//    @RequiresPermissions("system:danmoInformationCopy1:remove")
    @Log(title = "个人信息新", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public Result remove(@PathVariable Long[] ids)
    {
        return danmoInformationCopy1Service.deleteDanmoInformationCopy1ByIds(ids);
    }


    /**
     * 年份
     */
    @PostMapping("/selectListyears")
    public Result selectListyears(@RequestBody DanmoInformationCopy1 danmoInformationCopy1){
        return Result.success(danmoInformationCopy1Service.selectListyears(danmoInformationCopy1));
    }

    /**
     * 历届
     */
    @PostMapping("/selectSuccessive")
    public  Result selectSuccessive(@RequestBody DanmoInformationCopy1 danmoInformationCopy1){
        return Result.success(danmoInformationCopy1Service.selectSuccessive(danmoInformationCopy1));
    }



    /**
     * 列表查询 省排序
     * @param danmoInformationCopy1
     * @return
     */
    @PostMapping("/select")
    public Result select(@RequestBody DanmoInformationCopy1 danmoInformationCopy1) {
        List<?> list = new ArrayList<>();
        try {
            list = aggregationService.performAggregationQuery(personMapper.to(danmoInformationCopy1));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
//        List<Map<String, Object>> select = danmoInformationCopy1Service.select(danmoInformationCopy1);
        return Result.success(list);
    }

    /**
     * 列表查询名字排序
     * @param danmoInformationCopy1
     * @return
     */
    @PostMapping("/selectList")
    public Result  selectList(@RequestBody DanmoInformationCopy1 danmoInformationCopy1){
        List<Map<String, List<DanmoInformationCopy1>>> list = danmoInformationCopy1Service.selectList(danmoInformationCopy1);
        return Result.success(list);
    }

    /**
     * 查询理事会名单
     */
    @PostMapping("/selectCouncil")
    public Result selectAncient(@RequestBody DanmoInformationCopy1 danmoInformationCopy1) {
        List<Map<String, Object>> maps = danmoInformationCopy1Service.selectCouncil(danmoInformationCopy1);
        return Result.success(maps);
    }

    /**
     * 查询省理事会名单
     */
    @PostMapping("/selectProvince")
    public Result selectProvince(@RequestBody DanmoInformationCopy1 danmoInformationCopy1) {
        DanmoProvincesCities danmoProvincesCities = danmoInformationCopy1Service.selectProvince(danmoInformationCopy1);
        return Result.success(danmoProvincesCities);
    }

    /**
     * 查询区名单 名字排序
     */
    @PostMapping("/selectCounty")
    public Result selectCounty(@RequestBody DanmoInformationCopy1 danmoInformationCopy1) {
        // 获取数据
        DanmoProvincesCities<List<Map<String, List<PersonBaseInfoVO>>>> list = danmoInformationCopy1Service.selectCounty(danmoInformationCopy1);
        return Result.success(list);
    }
    /**
     * 查询省名单 名字排序
     */
    @PostMapping("/selectProvinceList")
    public Result selectProvinceList(@RequestBody DanmoInformationCopy1 danmoInformationCopy1) {
        // 获取数据
//        DanmoProvincesCities<List<Map<String, List<DanmoInformationCopy1>>>> list = danmoInformationCopy1Service.selectProvinceList(danmoInformationCopy1);
        Map<String,Object> detailMember;
        try {
            detailMember = aggregationService.findDetailMember(personMapper.to(danmoInformationCopy1));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Result.success(detailMember);
    }

    /**
     * 查询区理事会名单
     */
    @PostMapping("/selectCouncilCounty")
    public Result selectCouncilCounty(@RequestBody DanmoInformationCopy1 danmoInformationCopy1) {
        // 获取数据
        DanmoProvincesCities danmoProvincesCities = danmoInformationCopy1Service.selectCouncilCounty(danmoInformationCopy1);
        return Result.success(danmoProvincesCities);
    }

    /**
     * 查询市理事会名单
     */
    @PostMapping("/selectCouncilCity")
    public Result selectCouncilCity(@RequestBody DanmoInformationCopy1 danmoInformationCopy1) {
        // 获取数据
        DanmoProvincesCities danmoProvincesCities = danmoInformationCopy1Service.selectCouncilCity(danmoInformationCopy1);
        return Result.success(danmoProvincesCities);
    }

    /**
     *查询省市
     */
     @PostMapping("/queryProvincesCities")
     public Result queryProvincesCities(@RequestBody DanmoInformationCopy1 danmoInformationCopy1){
//         List<Map<String, Object>> maps = danmoInformationCopy1Service.queryProvincesCities(danmoInformationCopy1);
         List<?> city;
         try {
             city = aggregationService.findCity(personMapper.to(danmoInformationCopy1));
         } catch (IOException e) {
             throw new RuntimeException(e);
         }
         return Result.success(city);
     }

    /**
     * 查询市人名
     * @param danmoInformationCopy1
     * @return
     */
     @PostMapping("selectCity")
     public Result selectCity(@RequestBody DanmoInformationCopy1 danmoInformationCopy1){
         DanmoProvincesCities<List<Map<String, List<DanmoInformationCopy1>>>> list = danmoInformationCopy1Service.selectCity(danmoInformationCopy1);
         return Result.success(list);
     }


    /**
     * 查询社团理事会
     */
    @PostMapping("/selectGreekCouncil")
    public Result selectGreekCouncil(@RequestBody DanmoInformationCopy1 danmoInformationCopy1) {
        // 获取数据
        DanmoProvincesCities danmoProvincesCities = danmoInformationCopy1Service.selectGreekCouncil(danmoInformationCopy1);
        return Result.success(danmoProvincesCities);
    }


    /**
     * 查询社团名单
     */
    @PostMapping("/checkClubsList")
    public Result checkClubsList(@RequestBody DanmoInformationCopy1 danmoInformationCopy1) {
        DanmoProvincesCities danmoProvincesCities = danmoInformationCopy1Service.checkClubsList(danmoInformationCopy1);
        return Result.success(danmoProvincesCities);

    }
    /**
     * 查询个人信息  selectInformationPortfolio
     *
     * @param danmoInformationCopy1
     * @return
     */
    @PostMapping("/selectInformationPortfolio")
    public Result selectInformationPortfolio(@RequestBody DanmoInformationCopy1 danmoInformationCopy1) {
        return  danmoInformationCopy1Service.selectDanmoInformationCopy1ById(danmoInformationCopy1);
    }

    /**
     * 查询古代名字
     * @param danmoInformationCopy1
     * @return
     */

    @PostMapping("/searchAncientNames")
    public  Result searchAncientNames(@RequestBody DanmoInformationCopy1 danmoInformationCopy1){
        List<Map<String, List<DanmoInformationCopy1>>> maps = danmoInformationCopy1Service.searchAncientNames(danmoInformationCopy1);
        return Result.success(maps);
    }


    /**
     * 查询书法艺术爱好者
     */
    @PostMapping("/CheckCalligraphyEnthusiasts")
    public Result CheckCalligraphyEnthusiasts(@RequestBody DanmoInformationCopy1 danmoInformationCopy1) {
        List<Map<String, List<DanmoInformationCopy1>>> danmoProvincesCities = danmoInformationCopy1Service.CheckCalligraphyEnthusiasts(danmoInformationCopy1);
        return Result.success(danmoProvincesCities);
    }


    /**
     * 查询自己是否有个人信息
     */
    @PostMapping("/selectDanmoInformationReq")
    public Result selectDanmoInformationReq(@RequestBody DanmoInformationCopy1 danmoInformationCopy1) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser==null){
            return Result.notLoggedIn("请登录");
        }
        Long userid = loginUser.getUserid();
        danmoInformationCopy1.setUserId(userid);
        DanmoInformationCopy1 o = danmoInformationCopy1Service.selectDanmoInformationReq(danmoInformationCopy1);
        return Result.success(o);
    }

    /**
     *  查看自己的信息
     */
    @PostMapping("/selectUser")
    public Result selectUser(@RequestBody DanmoInformationCopy1 danmoInformationCopy1) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser==null){
            return Result.notLoggedIn("请登录");
        }
        Long userid = loginUser.getUserid();
        danmoInformationCopy1.setUserId(userid);
        DanmoInformationCopy1  o = danmoInformationCopy1Service.selectUser(danmoInformationCopy1);
        return Result.success(o);
    }


    private static final String ID_CARD_PATTERN = "^(\\d{15}|\\d{17}[0-9Xx])$";
    private static final String CHINESE_NAME_PATTERN = "^[\\u4e00-\\u9fa5]{2,15}$"; // 姓名长度在2-30个汉字之间

    /**
     * 人脸识别
     */
    @PostMapping("/faceRecognition")
    public Result faceRecognition(@RequestBody DanmoInformationCopy1 danmoInformationCopy1) throws Exception {

       if (danmoInformationCopy1.getName()==null|| danmoInformationCopy1.getName().equals("")){
           return Result.error("请输入姓名");
       }

        // 使用正则表达式检查是否为中文姓名
        if (!Pattern.matches(CHINESE_NAME_PATTERN, danmoInformationCopy1.getName())) {
            return Result.error("姓名只能包含中文字符，且长度为2到15个字符");
        }

        if (danmoInformationCopy1.getIdCard()==null|| danmoInformationCopy1.getIdCard().equals("") ){
           return Result.error("请输入身份证号码");
       }

        // 判断身份证号码是否符合格式
        Pattern pattern = Pattern.compile(ID_CARD_PATTERN);
        Matcher matcher = pattern.matcher(danmoInformationCopy1.getIdCard());
        if (!matcher.matches()) {
            return Result.error("身份证号码格式不正确");
        }

        // 进一步检查18位身份证的校验位（如果是18位）
        if (danmoInformationCopy1.getIdCard().length() == 18) {
            if (!isValidCheckDigit(danmoInformationCopy1.getIdCard())) {
                return Result.error("身份证号码校验位不正确");
            }
        }
        return InitFaceVerify.initializeFaceVerify(danmoInformationCopy1.getName(), danmoInformationCopy1.getIdCard());
    }
    // 校验18位身份证的校验位
    private static boolean isValidCheckDigit(String idCard) {
        // 身份证号码的加权因子（用于计算校验位）
        int[] weights = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
        // 校验位的值
        char[] checkDigits = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};

        // 计算前17位的加权和
        int sum = 0;
        for (int i = 0; i < 17; i++) {
            sum += Character.getNumericValue(idCard.charAt(i)) * weights[i];
        }

        // 计算校验位
        int remainder = sum % 11;
        char checkDigit = checkDigits[remainder];

        // 校验输入的身份证最后一位是否与计算得到的校验位一致
        return checkDigit == idCard.charAt(17);
    }
    /**
     * 获取认证信息
     * @param getCertifyId
     * @return
     */

    @PostMapping("/describeFaceVerify/{getCertifyId}")
    public Result selectList(@PathVariable String getCertifyId, @RequestBody DanmoInformationCopy1 danmoInformationCopy1) throws Exception {
            // 调用人脸认证查询方法
        Result result = DescribeFaceVerify.describeFaceVerify(getCertifyId);

        // 检查认证信息是否有效
            if (result == null || result.getData() == null) {
                return Result.error("认证信息获取失败");
            }


        // 获取认证信息


        // 获取认证状态、姓名和身份证号码
            String passed = result.getData().toString();;
//
            // 如果认证不通过，返回错误信息
            if ("F".equals(passed)) {
                return Result.error("人脸识别未通过");
            }else {
                 danmoInformationCopy1.setRealName(1L);
                 danmoInformationCopy1.setCreateTime(DateUtils.getNowDate());
                addDanmoInformation(danmoInformationCopy1);

                // 返回认证信息及成功状态
                return Result.success(passed, "人脸识别成功");
            }
    }

    /**
     * 添加详细信息
     * @param danmoInformationCopy1
     * @return
     */
   @PostMapping("addFurther")
    public Result addFurther(@RequestBody DanmoInformationCopy1 danmoInformationCopy1) throws UnsupportedEncodingException {

       LoginUser loginUser = SecurityUtils.getLoginUser();
       if (loginUser==null){
           return Result.notLoggedIn("请登录");
       }
       Long userid = loginUser.getUserid();
       DanmoInformationCopy1 danmoInformationCopy11 = new DanmoInformationCopy1();
       danmoInformationCopy11.setUserId(userid);
       danmoInformationCopy11.setAssociationType(danmoInformationCopy1.getAssociationType());
       DanmoInformationCopy1 danmoInformationCopy12 = danmoInformationCopy1Service.obtainPersonal(danmoInformationCopy11);
       if (danmoInformationCopy12==null){
           return Result.error("请先上传个人信息");
       }

      return danmoInformationCopy1Service.addFurther(danmoInformationCopy1,danmoInformationCopy12.getId());

   }


    /**
     * 查看个人信息详情
     * @param danmoInformationCopy1
     * @return
     */
    @PostMapping("/obtainPersonal")
    public Result<DanmoInformationCopy1> obtainPersonal(@RequestBody DanmoInformationCopy1 danmoInformationCopy1)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser==null){
            return Result.notLoggedIn("请登录");
        }
        return Result.success(danmoInformationCopy1Service.obtainPersonal(danmoInformationCopy1));
    }

    @PostMapping("/danmoUserList")
    public List<DanmoInformationCopy1> danmoInformationCopy1List(@RequestBody List<Long> longs) {
        List<DanmoInformationCopy1> danmoInformationCopy1List = danmoInformationCopy1Service.selectUserIdList(longs);
        return danmoInformationCopy1List;
    }

}
